var express = require('express');
var bodyParser = require('body-parser');
// 引入自定义db函数
var db = require('./db');


var app = express();

app.use(bodyParser.urlencoded({extended: true})) 

//设置允许跨域访问该服务.
app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  //Access-Control-Allow-Headers ,可根据浏览器的F12查看,把对应的粘贴在这里就行
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  res.header('Access-Control-Allow-Methods', '*');
  res.header('Content-Type', 'application/json;charset=utf-8');
  next();
});


app.set('view engine', 'html');

app.get('/', function(req, res) {
    res.sendFile(__dirname + "/index.html");
});

app.post('/', function(req, res) {
    res.send('post 请求');
});

app.get('/fits', function(req, res) {
    console.log("get");

    console.log(req.query);

    // 连接数据库
    db.connect();

    var sql = "SELECT * FROM fit";

    db.select(sql, function(err, result) {
        if (!err) {
            var obj = {
                code: 0,
                msg: "查询成功",
                list: result
            }

            res.send(JSON.stringify(obj));
        } else {
            var obj = {
                code: -1,
                msg: '查询失败'
            };
            res.send(JSON.stringify(obj));
        }
    });

    // 关闭数据库
    db.disconnect();
});

app.post('/fits', function(req, res) {
    console.log("post");
    console.log(req.body);

    // 连接数据库
    db.connect();

    var sql = "SELECT * FROM fit";

    db.select(sql, function(err, result) {
        if (!err) {
            var obj = {
                code: 0,
                msg: "查询成功",
                list: result
            }

            res.send(JSON.stringify(obj));
        } else {
            var obj = {
                code: -1,
                msg: '查询失败'
            };
            res.send(JSON.stringify(obj));
        }
    });

    // 关闭数据库
    db.disconnect();
});


app.listen(8080);